package cn.fcq.basic.interceptor;

import cn.fcq.basic.anno.PreAuthorize;
import cn.fcq.basic.jwt.JwtUtils;
import cn.fcq.basic.jwt.LoginResult;
import cn.fcq.basic.jwt.Payload;
import cn.fcq.basic.jwt.RsaUtils;
import cn.fcq.system.mapper.PermissionMapper;
import cn.fcq.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${rsa.pub}")
    private String publicKeyValue;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从请求头中获取 U-TOKEN
        String token = request.getHeader("U-TOKEN");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        if (StringUtils.hasLength(token)) {
            /*//3.根据U-TOKEN从redis中获取登录信息
            Object loginTmp = redisTemplate.opsForValue().get(token);*/
            //解密jwt串获取登录人信息和权限
            //获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            //使用公钥解密jwt串
            Payload<LoginResult> payload = JwtUtils.getInfoFromToken(token, publicKey, LoginResult.class);
            LoginResult loginResult = payload.getUserInfo();
            if (loginResult != null) {
                // 登录之后，校验是否有权限访问某个资源
               // Logininfo logininfo = (Logininfo) loginTmp;
                Logininfo logininfo = loginResult.getLogininfo();
                //1.校验是否是员工，是就要校验权限
                if (logininfo.getType()==0){
                    //2.获取当前请求的url
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize annotation = method.getMethodAnnotation(PreAuthorize.class);
                    if (annotation !=null){
                        String currentSn = annotation.value();
                        //查询出当前登录人的权限资源permissions
                       // List<String> permissionss = permissionMapper.loadPermissionByLogininfoId(logininfo.getId());
                        //判断当前资源permissions是否包含url
                        if (!loginResult.getPermissions().contains(currentSn)){
                            //不包含，提示权限不足
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"nopermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                }
                //刷新过期时间
               /* redisTemplate.opsForValue().set(
                        token,
                        loginTmp,
                        30,
                        TimeUnit.MINUTES
                );*/
                return true;//登陆了 放行
            }
        }
        //2.登录
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行

    }
}